package com.comm;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class HttpContextUtil {

    /*获取请求服务器的属性信息*/
    public static HttpServletRequest getRequest(){
        return ((ServletRequestAttributes)(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    /*根据属性获取IP地址*/
    public static String getIPAddress(){
        HttpServletRequest request=getRequest();
        String ip=request.getHeader("s-forwarder-for");
        if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip) ){
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip) ){
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip) ){
            ip = request.getHeader("HTTP-Client-IP");
        }
        if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip) ){
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip) ){
            ip = request.getRemoteAddr();
        }

        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" :ip;
    }
}